<template>
  <el-row class="user-info-form" type="flex" justify="center">
    <el-col>
      <el-form
        label-position="top"
        :model="editForm"
        :rules="editFormRules"
        ref="editForm"
        @submit.native.prevent
      >
        <input type="hidden" v-model="editForm.id" />
        <el-form-item v-if="isMuilUnitUser" label="业主单位：" prop="orgId">
          <el-select
            clearable
            filterable
            v-model="editForm.orgId"
            placeholder="请选择业主单位"
            @change="handleOrgChange"
          >
            <el-option
              v-for="item in orgOptions"
              :key="item.organizationId"
              :label="item.shortName"
              :value="item.organizationId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="巡检计划名称：" prop="name">
          <el-input v-model="editForm.name" auto-complete="off" placeholder="请输入计划名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="开始与结束日期" required>
          <el-col :span="11">
            <el-form-item prop="startDate">
              <el-form-item>
                <el-date-picker
                  v-model="editForm.startDate"
                  value-format="yyyy-MM-dd"
                  style="width: 100%;"
                  type="date"
                  placeholder="设定计划开始"
                  :picker-options="pickerOptions"
                ></el-date-picker>
              </el-form-item>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="2">-</el-col>
          <el-col :span="11">
            <el-form-item prop="endDate">
              <el-date-picker
                v-model="editForm.endDate"
                value-format="yyyy-MM-dd"
                style="width: 100%;"
                type="date"
                placeholder="设定计划结束"
                :picker-options="pickerOptions"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="巡检类型：">
          <el-radio-group v-model="editForm.planType">
            <el-radio label="1">一天一次巡检</el-radio>
            <!-- 多条路线  -->
            <el-radio label="2">一天多次巡检</el-radio>
            <!-- 一条路线、设置巡检时间间隔 -->
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="editForm.planType==2" label="设置巡检时间间隔（小时）：" required>
          <el-input-number v-model="editForm.planPeriod" :min="1" :max="24"></el-input-number>
        </el-form-item>
        <el-form-item label="巡检路线：" v-if="editForm.planType==1">
          <el-select filterable v-model="checkedRoutes" multiple>
            <el-option
              v-for="item in routeOptions"
              :key="item.id.toString()"
              :label="item.routeName"
              :value="item.id.toString()"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="巡检路线：" v-if="editForm.planType==2">
          <el-select filterable v-model="editForm.planRoutesId">
            <el-option
              v-for="item in routeOptions"
              :key="item.id.toString()"
              :label="item.routeName"
              :value="item.id.toString()"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设置工作日和每天的工作时间：">
          <el-row>
            <el-col :span="5">
              <el-checkbox v-model="checkedWorkingDay">周一到周五</el-checkbox>
            </el-col>
            <el-col :span="3">开始时间</el-col>
            <el-col :span="5">
              <el-time-picker
                v-model="timeWorkingDay"
                :clearable="false"
                size="mini"
                value-format="HH:mm:ss"
                format="HH:mm"
              ></el-time-picker>
            </el-col>
            <el-col :span="4" style="text-align: right;">持续（小时）</el-col>
            <el-col :span="4">
              <el-input-number size="mini" v-model="durationWorkingDay" :min="1" :max="24"></el-input-number>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="5">
              <el-checkbox v-model="checkedSaturday">周六</el-checkbox>
            </el-col>
            <el-col :span="3">开始时间</el-col>
            <el-col :span="5">
              <el-time-picker
                v-model="timeSaturday"
                :clearable="false"
                size="mini"
                value-format="HH:mm:ss"
                format="HH:mm"
              ></el-time-picker>
            </el-col>
            <el-col :span="4" style="text-align: right;">持续（小时）</el-col>
            <el-col :span="4">
              <el-input-number size="mini" v-model="durationSaturday" :min="1" :max="24"></el-input-number>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="5">
              <el-checkbox v-model="checkedSunday">周日</el-checkbox>
            </el-col>
            <el-col :span="3">开始时间</el-col>
            <el-col :span="5">
              <el-time-picker
                v-model="timeSunday"
                :clearable="false"
                size="mini"
                value-format="HH:mm:ss"
                format="HH:mm"
              ></el-time-picker>
            </el-col>
            <el-col :span="4" style="text-align: right;">持续（小时）</el-col>
            <el-col :span="4">
              <el-input-number size="mini" v-model="durationSunday" :min="1" :max="24"></el-input-number>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label-width="0" class="verifyidentity-button">
          <el-button round @click="closeDialog()">取消</el-button>
          <el-button type="primary" round @click="savePointType('editForm')">确定</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<script>
import util from '@/utils/util'
import { getUsers } from '@/api/api'
import { getDictByCode } from '@/api/dic'
import { getFbsTree } from '@/api/fbs'
import * as Dao from '@/api/inspect'
import TreeSelect from '@/libs/TreeSelect/Main'
import { getOrgList } from '@/api/org'

export default {
  name: 'InspectAreaForm',
  components: {
    TreeSelect,
  },
  props: {
    organizationId: {
      required: false,
    },
    editInfo: {
      type: Object,
      required: false,
    },
    closeDialog: {
      type: Function,
      required: true,
    },
  },
  data() {
    return {
      pickerOptions: $.extend(
        {
          disabledDate(time) {
            return time.getTime() < new Date().setHours(0, 0, 0, 0) //不小于今天
          },
        },
        util.intDatePickerOptions(true)
      ),
      buildList: [],
      util: util,
      checkedWorkingDay: false,
      checkedSaturday: false,
      checkedSunday: false,
      timeWorkingDay: '08:30:00',
      timeSaturday: '08:30:00',
      timeSunday: '08:30:00',
      durationWorkingDay: 1,
      durationSaturday: 1,
      durationSunday: 1,
      routeOptions: [],
      checkedRoutes: [],
      editForm: {
        id: '',
        orgId: '',
        name: '',
        startDate: '',
        endDate: '',
        planPeriod: 1,
        planRoutesId: '',
        workingDay: '', //08:30:00,1
        saturday: '', //08:30:00,1
        sunday: '', //08:30:00,1
        planType: '1',
        status: 0,
      },
      editFormRules: {
        /*planRoutesId: [
                { required: true, message: '请选择路线类型', trigger: 'blur' }
            ],*/
        orgId: [{ required: true, message: '请选择业主单位' }],
        name: [{ required: true, message: '请输入路线名称', trigger: 'blur' }],
        startDate: [
          {
            type: 'string',
            required: true,
            message: '请选择日期',
            trigger: 'change',
          },
        ],
        endDate: [
          {
            type: 'string',
            required: true,
            message: '请选择日期',
            trigger: 'change',
          },
        ],
      },
      isMuilUnitUser: this.$store.state.userinfo.isMuilUnitUser,
      orgOptions: [],
    }
  },
  created() {
    let infoObj = this.editInfo
    let that = this
    //绑定下拉框
    if (this.isMuilUnitUser) {
      getOrgList({ queryType: 0 }).then((data) => {
        this.orgOptions.push.apply(this.orgOptions, data.data)
      })
    } else {
      this.editForm.orgId = this.$store.state.userinfo.org.id
    }

    if (infoObj.id) {
      //编辑
      that.editForm.id = infoObj.id
      that.editForm.name = infoObj.name
      that.editForm.orgId = infoObj.orgId
      that.editForm.startDate = infoObj.startDate
      that.editForm.endDate = infoObj.endDate
      that.editForm.planPeriod = infoObj.planPeriod
      that.checkedRoutes = infoObj.planRoutesId.toString().split(',')
      that.editForm.planType = infoObj.planType.toString()
      if (infoObj.planType == 2) {
        //1-多条路线 2-一条路线
        that.editForm.planRoutesId = infoObj.planRoutesId.toString()
      } else {
        //多条路线取第一条给单选下拉框赋值
        that.editForm.planRoutesId = infoObj.planRoutesId
          .toString()
          .split(',')[0]
      }
      that.editForm.status = infoObj.status
      $.each(infoObj.workTimeList, function (index, val) {
        if ([1, 2, 3, 4, 5].indexOf(val.dayOfWeek) > -1) {
          that.checkedWorkingDay = true
          that.timeWorkingDay = val.workStartTime.substr(0, 5) + ':00'
          that.durationWorkingDay = val.workContinueTime || 1
        } else if (val.dayOfWeek == 6) {
          that.checkedSaturday = true
          that.timeSaturday = val.workStartTime.substr(0, 5) + ':00'
          that.durationSaturday = val.workContinueTime || 1
        } else if (val.dayOfWeek == 7) {
          that.checkedSunday = true
          that.timeSunday = val.workStartTime.substr(0, 5) + ':00'
          that.durationSunday = val.workContinueTime || 1
        }
      })
    }

    this.getData()
  },
  methods: {
    handleOrgChange() {
      this.checkedRoutes = []
      this.editForm.planRoutesId = ''
      this.getData()
    },
    getData() {
      if (!this.editForm.orgId) return
      Dao.getInspectRouteList({
        orgIds: this.editForm.orgId,
        queryType: 0,
      }).then((data) => {
        this.routeOptions = data.data
      })
    },
    savePointType(formName) {
      // 阻止事件冒泡
      event.stopPropagation()
      let that = this
      that.$refs[formName].validate((valid) => {
        if (valid) {
          let parames = that.editForm
          if (parames.planType == 1) {
            parames.planRoutesId = that.checkedRoutes.join(',')
          }
          if (that.checkedWorkingDay) {
            parames.workingDay =
              this.timeWorkingDay + ',' + this.durationWorkingDay
          }
          if (that.checkedSaturday) {
            parames.saturday = this.timeSaturday + ',' + this.durationSaturday
          }
          if (that.checkedSunday) {
            parames.sunday = this.timeSunday + ',' + this.durationSunday
          }
          Dao.updateInspectPlan(parames).then((res) => {
            if (res.status === 200) {
              that.$message({
                message: '保存成功！',
                type: 'success',
              })
            } else {
              this.$message.error(res.info)
            }
            that.closeDialog(true)
          })
        } else {
          return false
        }
      })
    },
  },
}
</script>